import pymysql

host='localhost'
port=3308
user='root'
password='123456'
database='cz'
charset='utf8'

db=pymysql.Connect(host=host,port=port,user=user,password=password,database=database,charset=charset)
print('数据库已链接')

# 插入数据
username='cz'
phone='15239925869'
sql=f"""
insert into tb3 values(null,'{username}','{phone}')
"""
cursor=db.cursor()
try:
    cursor.execute(sql)
    db.commit()
    print('数据已插入')
except Exception as e:
    db.rollback()
    print(e)

# 修改数据
# username='cz'
# phone='15239925868'
# sql=f"""
# update tb3 set phone='{phone}' where username = '{username}'
# """
# try:
#     cursor.execute(sql)
#     db.commit()
#     print('数据已修改')
# except Exception as e:
#     db.rollback()
#     print(e)

# 删除数据
# username='cz'
# sql=f"""
# delete from tb3 where username='{username}'
# """
# try:
#     cursor.execute(sql)
#     db.commit()
#     print('数据已删除')
# except Exception as e:
#     db.rollback()
#     print(e)


# 查询数据
sql="""
select * from tb3
"""
try:
    rows=cursor.execute(sql)
    data=cursor.fetchall()
    # db.commit()
    print('数据查询成功')
except Exception as e:
    # db.rollback()
    print(e)
print(rows)
for row in data:
    print(f"{row[1]}---{row[2]}")
# print(data)
cursor.close()
db.close()


